const scoreDom = document.querySelector(".score");
const difficultyDom = document.querySelector("#difficulty-select");
const startButton = document.getElementById("start-button"); // 获取开始按钮

// 获取cookie辅助函数
function getCookie(name) {
  const cookieArr = document.cookie.split(";");
  const cookies = cookieArr.reduce((pre, item) => {
    const itemCookie = item.trim().split("=");
    pre[itemCookie[0]] = itemCookie[1];
    return pre;
  }, {});
  return cookies[name] || null;
}

// 游戏类
class Game {
  constructor() {
    this.difficulty = getCookie("difficulty") || 1; // 难度
    this.baseSpeed = -100; // 基础速度
    this.init();
    this.difficultyChange(); // 监听难度变化
  }

  init() {
    this.sky = new Sky(-60 * this.difficulty);
    this.land = new Land(-100 * this.difficulty);
    this.bard = new Bard();
    //柱子对生成器
    this.pipeProducer = new PipePareProducer({
      speed: -100 * this.difficulty,
      tick: 1800 / this.difficulty,
    });
    //道具生成
    this.propList = new PropPareProducer(-100 * this.difficulty, 1800);

    this.tick = 16; // 移动的时间间隔，毫秒
    this.timer = null;
    this.gameOver = false; // 游戏结束
    this.price = 0; // 分数
    scoreDom.innerHTML = this.price; // 初始化渲染分数

    // 初始化难度选中状态
    for (let i = 0; i < difficultyDom.options.length; i++) {
      if (difficultyDom.options[i].value === this.difficulty) {
        difficultyDom.options[i].selected = true;
        break; // 找到后退出循环
      }
    }
  }

  upSpeed(difficulty) {
    if (difficulty) {
      this.difficulty = difficulty;
    }
    this.sky.xSpeed = this.baseSpeed * 0.6 * this.difficulty;
    this.land.xSpeed = this.baseSpeed * this.difficulty;
    this.propList.speed = this.baseSpeed * this.difficulty;
    this.pipeProducer.speedChange(this.difficulty);
  }

  checkSpeedIncrease(difficulty) {
    if (difficulty) {
      this.difficulty = difficulty;
    }
    // 每得100分增加10%的速度
    const speedMultiplier = 1 + Math.floor(this.price / 100) * 0.1;
    const newSpeed = this.baseSpeed * this.difficulty * speedMultiplier;

    this.sky.xSpeed = newSpeed * 0.6;
    this.land.xSpeed = newSpeed;
    this.propList.speed = newSpeed;
    console.log(newSpeed);

    this.pipeProducer.speedChange(this.difficulty, speedMultiplier);
  }

  difficultyChange() {
    difficultyDom.onchange = (e) => {
      const val = e.target.value;
      this.difficulty = val;
      document.cookie = `difficulty=${val}`;
      // 修改难度后移除之前的水管
      this.pipeProducer.pares.forEach((pare) => {
        pare.upPaie.dom.remove();
        pare.downPaie.dom.remove();
      });
      this.stop(); // 停止之前的游戏
      this.init(); // 初始化
    };
  }

  setPrice(price = 10) {
    this.price += price;
    scoreDom.innerHTML = this.price;
  }

  // 开始游戏
  start() {
    if (this.timer) {
      return;
    }
    if (this.gameOver) {
      //重新开始游戏
      window.location.reload();
    }
    const duration = this.tick / 1000;
    this.pipeProducer.startRender();
    this.propList.startRender({ game: this });
    this.timer = setInterval(() => {
      this.sky.move(duration);
      this.land.move(duration);
      this.bard.move(duration);

      this.pipeProducer.pares.forEach((pare) => {
        pare.move(duration);
        const distance = pare.upPaie.left + pare.upPaie.width;
        if (
          distance <= this.bard.left &&
          Math.abs(distance - this.bard.left) < 100 * duration * this.difficulty
        ) {
          this.setPrice();
          this.checkSpeedIncrease(); // 检查是否需要增加速度
        }
      });

      // 觸碰道具檢測
      this.propList.pares.forEach((pare, i) => {
        const { prop, type } = pare;
        prop.move(duration);
        if (
          this.bard.left < prop.left + prop.width &&
          this.bard.left + this.bard.width > prop.left &&
          this.bard.top < prop.top + prop.height &&
          this.bard.top + this.bard.height > prop.top
        ) {
          this.propList.removeProp(prop.dom, i);

          this.propEffect(type);
        }
      });

      // 鳥碰撞检测
      if (this.isGameOver()) {
        this.stop();
        this.gameOver = true;
        this.overText();
      }
    }, this.tick);
  }

  stop() {
    clearInterval(this.timer);
    this.timer = null;
    this.pipeProducer.stopProduce();
    this.propList.stopProduce();
    startButton.style.display = "block"; // 显示开始按钮
  }

  /**道具生效 */
  propEffect(type) {
    if (type == "opacity") {
      this.bard.pipeOpacity({ game: this, time: 8 });
    } else if (type == "sprint") {
      this.bard.sprint({ time: 5, game: this });
    } else if (type == "protect") {
      this.bard.renderProtect(true);
    }
  }

  /**
   * 注册按键事件
   */
  regEvent() {
    window.onkeydown = (e) => {
      if (e.key === "Enter") {
        if (this.timer) {
          this.stop();
        } else {
          this.start();
        }
      } else if (e.key === " ") {
        this.bard.jump();
      }
    };

    // 添加点击游戏区域小鸟跳跃的事件监听器
    // 使用 touchstart 事件来替代 click 事件
    document.querySelector(".game").addEventListener("touchstart", (e) => {
      // 检查点击的目标是否是开始按钮
      if (e.target.id !== "start-button") {
        e.preventDefault(); // 阻止默认行为，防止滚动等
        this.bard.jump();
      }
    });
  }

  // 判断鸟与水管是否相撞
  // isHit(rec1, rec2) {
  //   // 横向：两个矩形的中心点的横向距离，是否小于矩形宽度之和的一半
  //   // 纵向：两个矩形的中心点的纵向距离，是否小于矩形高度之和的一半
  //   const centerX1 = rec1.left + rec1.width / 2;
  //   const centerX2 = rec2.left + rec2.width / 2;
  //   const centerY1 = rec1.top + rec1.height / 2;
  //   const centerY2 = rec2.top + rec2.height / 2;
  //   var disX = Math.abs(centerX1 - centerX2); //中心点横向距离
  //   var disY = Math.abs(centerY1 - centerY2); //中心点纵向距离
  //   if (
  //     disX < (rec1.width + rec2.width) / 2 &&
  //     disY < (rec1.height + rec2.height) / 2
  //   ) {
  //     return true;
  //   }
  //   return false;
  // }

  // 判断鸟与水管是否相撞
  isHit(bard, pipe) {
    if (
      bard.left < pipe.left + pipe.width &&
      bard.left + bard.width > pipe.left &&
      bard.top < pipe.top + pipe.height &&
      bard.top + bard.height > pipe.top
    ) {
      return true;
    }
    return false;
  }

  isGameOver() {
    if (this.bard.top === this.bard.maxY) {
      // 鸟落地
      return true;
    }
    for (let i = 0; i < this.pipeProducer.pares.length; i++) {
      const pare = this.pipeProducer.pares[i];

      // 与上水管相撞或与下水管相撞
      const peng =
        this.isHit(this.bard, pare.upPaie) ||
        this.isHit(this.bard, pare.downPaie);

      if (this.bard.status === "sprint" && peng) {
        // 冲刺状态下碰到柱子，让柱子消失
        pare.upPaie.dom.remove();
        pare.downPaie.dom.remove();
        this.pipeProducer.pares.splice(i, 1);
        this.setPrice(10);
        return false;
      }

      if (!this.bard.miss && peng) {
        if (this.bard.protect) {
          this.bard.renderProtect(false);
          return false;
        }

        return true;
      }
    }

    return false;
  }

  overText() {
    const overDom = document.querySelector(".over");
    overDom.innerHTML = `鑫仔出品，必是精品<br/>游戏结束<br/>最终得分：${this.price}`;
  }
}

const g = new Game();
g.regEvent();

// 开始游戏函数
function startGame() {
  g.start();
  startButton.style.display = "none"; // 隐藏开始按钮
}
